#!/usr/bin/env python
# coding=utf-8
#import pymysql
#pymysql.install_as_MySQLdb()
#将数据层信息写入数据库

import MySQLdb
import time
import os
import json

def data():
	# 连接数据库
	conn = MySQLdb.connect(
		host='localhost',
		port=3306,
		user='root',
		passwd='cnv6201',
		db='PRESENTATION',
		charset='utf8',
		)
	cur = conn.cursor()

	# 清空数据库中表格内的信息
	cur.execute("delete from presentation_endata")
	cur.execute("delete from presentation_key")
	cur.execute("delete from presentation_file_list")
	# 打开data层JSON文件读取数据
	f = open('JsonFileReport/report_data.json', "r", encoding='UTF-8')
	data = json.load(f)

	# 向数据库中传入密钥随机化数据
	unsaltykey = data['layer_info']['random']['key']
	saltykey = data['layer_info']['random']['randomkey']
	cur.execute("insert into presentation_key(unsaltykey, saltykey) values(%s,%s)",
		[unsaltykey, saltykey])

	# 向数据库中传入明文以及加密数据
	plaintext = data['layer_info']['encrypt']['original']
	ciphertext = data['layer_info']['encrypt']['encrypted']
	cur.execute("insert into presentation_endata(plaintext, ciphertext) values(%s,%s)",
		[plaintext, ciphertext])

	# 向数据库中传入副本的相关信息
	for i in range(len(data['layer_info']['copies'])):
		textname = data['layer_info']['copies'][i]['filename']
		UserRight = data['layer_info']['copies'][i]['rwaccess']
		creationTime = data['layer_info']['copies'][i]['createtime']
		changeTime = data['layer_info']['copies'][i]['modifytime']
		cur.execute(
		"insert into presentation_file_list(textname,UserRight,creationTime,changeTime) values(%s,%s,%s,%s)",
		[textname, UserRight, creationTime, changeTime])

	f.close()
	cur.close()
	conn.commit()
	conn.close()
	print("data层数据存储成功")
